<template>
  <div class="box">
    <div class="header">
      <van-nav-bar
        title="购物车"
        left-arrow
        @click-left="$router.push('/home')"
      >
        <template #right>
          <van-popover
            v-model="showPopover"
            trigger="click"
            placement="bottom-end"
            theme="dark"
            :actions="actions"
            @select="onSelect"
          >
            <template #reference>
              <van-icon name="ellipsis" size="26" color="#000" />
            </template>
          </van-popover>
        </template>
        <template #left>
          <van-icon name="arrow-left" size="26" color="#000" />
        </template>
      </van-nav-bar>
    </div>
    <div class="main"  @scroll="scrollMe" ref="main">
      <div class="nothing" v-if="!empty">
        <van-empty
          class="custom-image"
          image="https://img01.yzcdn.cn/vant/custom-empty-image.png"
          description="购物车空空如也"
        />
      </div>
      <div class="hashing" v-else>
        <van-swipe-cell
          v-for="(item, index) in cartList"
          :key="index"
          :name="item.cartid"
          :before-close="beforeClose"
        >
          <van-checkbox
            v-model="item.flag"
            @click="seletOne(item.cartid, item.flag)"
          ></van-checkbox>
          <van-card
            :price="item.originprice"
            :title="item.proname"
            :thumb="item.img1"
          >
            <template #num>
              <van-stepper
                v-model="item.num"
                theme="round"
                button-size="22"
                disable-input
                @change="changeNum(item.cartid, item.num)"
              />
            </template>
          </van-card>
          <template #right>
            <van-button
              square
              text="删除"
              type="danger"
              class="delete-button"
            />
          </template>
        </van-swipe-cell>
        <div class="list">
          <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
  <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    @load="onLoad"
  >
  <p class="liked"> - - - - - - - 猜你喜欢 - - - - - - - - </p>
  <div class="prolist1">
   <ul>
    <li v-for="item in list" :key="item.cartid" @click="jumpTo(item.proid)">
       <img :src="item.img1" alt="" />
                <div class="jdcc">
                  <h4>
                    <div class="van-multi-ellipsis--l2">
                      
                      {{ item.proname }}
                    </div>
                  </h4>
                  <p class="price">￥{{ item.originprice }}</p>
                </div>
    </li>
    
   </ul>
   </div>
  </van-list>
</van-pull-refresh>
        </div>
        <div class="submit" v-if="!isShow">
          <van-submit-bar
            :price="getSum"
            button-text="提交订单"
            @submit="onSubmit"
          >
            <van-checkbox v-model="isAll"></van-checkbox>全选
          </van-submit-bar>
        </div>
        <div class="dele" v-else>
          <van-submit-bar label button-text="删除" @submit="onSubmit1">
            
            <van-checkbox v-model="isAll">全选</van-checkbox>
          </van-submit-bar>
        </div>
      </div>
    </div>
     <div class="top" v-if="scrollTop>400" @click="backTop"><van-icon name="back-top" /></div>
  </div>
</template>

<script>
import Vue from "vue";
import {
  Empty,
  Card,
  Stepper,
  SwipeCell,
  Checkbox,
  CheckboxGroup,
  SubmitBar,
  Dialog,
} from "vant";

Vue.use(Empty);
Vue.use(Card);
Vue.use(Stepper);
Vue.use(SwipeCell);
Vue.use(Checkbox);
Vue.use(CheckboxGroup);
Vue.use(SubmitBar);
Vue.use(Dialog);
import {
  cartList,
  doCartUpdate,
  doCartDelete,
  doSelectOne,
  doSelectAll,
  doDeleteAll,
  doReList
} from "../api/cart";

import { getAddOrder} from "../api/submit";
export default {
  name: "Cart",
  components: {},
  data() {
    return {
      empty: true,
     
      cartList: [],
      showPopover: false,
      isShow: false,

      actions: [
        { text: "管理", icon: "wap-home-o" },
        { text: "分享", icon: "share-o" },
      ],
        list: [],
      loading: false,
      finished: false,
      refreshing: false,
      scrollTop:0
    };
  },
  methods: {


 onLoad() {
        setTimeout(() => {
      doReList({ count: this.count, limitNum: 12 }).then((data) => {
            //this.proList=data.data.data
            this.loading = false;
            if (data.data.data.length == 0) {
              this.finished = true;
            } else {
              this.list = [...this.list, ...data.data.data];
              this.count++;
            }
          });
      }, 1000);
    },
    jumpTo(proid) {
      this.$router.push("/detail/" + proid);
    },
    onRefresh() {
      // 清空列表数据
      this.finished = false;

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true;
      this.onLoad();
    },
  scrollMe(){
      this.scrollTop=this.$refs.main.scrollTop
    },
    backTop(){
    
      this.timer=setInterval(()=>{
          if(this.$refs.main.scrollTop<=0){
          
        clearInterval(this.timer)
      }
        this.$refs.main.scrollTop-=100
      },15)
     
    },




    changeNum(cartid, num) {
      doCartUpdate({
        cartid: cartid,
        num: num,
      }).then(() => {});
    },
    getCartList() {
      if (localStorage.getItem("token")) {
        cartList({ userid: localStorage.getItem("userid") }).then((res) => {
          if (res.data.code == "10020") {
            this.empty = false;
          } else {
            this.empty = true;

            console.log(res.data.data);
            this.cartList = res.data.data;
          }
        });
      } else {
        this.$router.push("/login");
      }
    },

    beforeClose({ name, position, instance }) {
      switch (position) {
        case "right":
          Dialog.confirm({
            message: "确定删除吗？",
          })
            .then(() => {
              doCartDelete({ cartid: name }).then((res) => {
                console.log(res);
                if (res.data.code == "200") {
                  this.getCartList();
                }
              });
              instance.close();
            })
            .catch(() => {
              instance.close();
            });
          break;
      }
    },
    selectOne(cartid, flag) {
      doSelectOne({ cartid: cartid, flag: flag }).then((res) => {
        console.log(res);
      });
    },
    onSelect(action, index) {
      switch (index) {
        case 0:

          this.isShow = !this.isShow;
          break;
        case 1:
          break;

        default:
          break;
      }
    },
    onSubmit() {
              getAddOrder({userid:localStorage.getItem("userid")}).then((data)=>{
      console.log(data)
    this.$router.push("/submit/"+data.data.time) 
       
    })
   
    },
    onSubmit1() {
      if (this.isAll) {
        Dialog.confirm({
          message: "确定删除吗？",
        }).then(() => {
          doDeleteAll({
            token: localStorage.getItem("token"),
            userid: localStorage.getItem("userid"),
          }).then(() => {
            this.getCartList();
          });
        });
      }
    },
  },
  computed: {
    getSum() {
      let newl = this.cartList.filter((item) => item.flag);

      return newl.reduce((sum, item) => {
        return (sum += parseInt(item.originprice * item.num) * 100);
      }, 0);
  
 
    },
    isAll: {
      set(val) {
        this.cartList.forEach((item) => {
          item.flag = val;
        });
        doSelectAll({ userid: localStorage.getItem("userid"), type: val }).then(
          (res) => {
            console.log(res);
          }
        );
      },
      get() {
        return this.cartList.every((item) => item.flag == true);
      },
    },
  },
  created() {
    // 判断用户是否登陆
    if (localStorage.getItem("token")) {
      this.getCartList();
    } else {
      //  去到登陆页
      this.$router.push("/login");
    }
  },
};
</script>
<style scoped>
.custom-image .van-empty__image {
  width: 90px;
  height: 90px;
}
.delete-button {
  height: 100%;
}
::v-deep .van-swipe-cell__wrapper {
  display: flex;
  background: #fff;
}
::v-deep .van-checkbox {
  width: 0.3rem;
  background: #fff;
}
::v-deep .van-card {
  flex: 1;
}
.van-submit-bar {
  bottom: 50px;
}
.dele .van-checkbox {
 width: 3rem;
}
.prolist1 ul{
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.prolist1 li {
  width: 48%;
}
.prolist1 li img {
  width: 100%;
}
.liked{
  width: 100%;
  text-align: center;

  margin: .2rem;

 
}
.top{
  position: fixed;
  bottom: 1rem;
  right: 0.2rem;
  height: 0.3rem;
  width: 0.3rem;
  border: 1px solid #000;
  border-radius: 50%;
  text-align: center;
  line-height: 0.3rem;
}
</style>